class TabBox {
  constructor(domRoot, config) {
    this.domRoot = domRoot;
    this.config = config;

    /* 接收用户配置 */
    let { tabs, boxStyles } = config;
    this.tabConfs = tabs; //
    this.boxStyles = boxStyles;

    // 渲染视图
    this.render();

    // 找出要做交互的元素
    this.findElements();

    // 添加互动
    this.initListeners();
  }

  render() {
    let tabsStr = "",
      contentsStr = "";

    this.tabConfs.forEach(
      // (item,index)=>{
      ({ tab, content }, index) => {
        tabsStr += `<li class=${index === 0 ? "active" : ""}>${tab}</li>`;
        contentsStr += `<li class=${
          index === 0 ? "active" : ""
        }>${content}</li>`;
      }
    );

    this.domRoot.innerHTML = `
        <div class="box">
            <ul id="ulTabs">
                ${tabsStr}
            </ul>
            <ol id="olContents">
                ${contentsStr}
            </ol>
        </div>
        `;
  }

  findElements() {
    /* 找出tabs对应的所有li元素 */
    this.tabLis = this.domRoot.querySelectorAll("ul>li");
    this.contentLis = this.domRoot.querySelectorAll("ol>li");
  }

  initListeners() {
    Array.from(this.tabLis).forEach((tab, index) => {
      // 务必使用箭头函数 以确保this依然指向tb对象 而非DOM事件源
      tab.onclick = (e) => {
        this.switchTab(index);
      };
    });
  }

  switchTab(index) {
    // 所有的标签取消高亮
    this.tabLis.forEach((li) => li.classList.remove("active"));
    // 所有的内容取消高亮
    this.contentLis.forEach((li) => li.classList.remove("active"));

    // index对应的标签添加高亮
    this.tabLis[index].classList.add("active");
    // index对应的内容添加高亮
    this.contentLis[index].classList.add("active");
  }
}
